package top.zyx.rpc.registry.ZK;

import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.CuratorFramework;
import top.zyx.rpc.entity.RpcRequest;
import top.zyx.rpc.enumeration.RpcError;
import top.zyx.rpc.exception.RpcException;
import top.zyx.rpc.loadbalance.LoadBalance;
import top.zyx.rpc.loadbalance.loadbalancer.RandomLoadBalancer;
import top.zyx.rpc.registry.ServiceDiscovery;
import top.zyx.rpc.util.CuratorUtils;

import java.net.InetSocketAddress;
import java.util.List;
@Slf4j
public class ZKServiceDiscovery implements ServiceDiscovery {
    private final LoadBalance loadBalancer;

    public ZKServiceDiscovery(LoadBalance loadBalancer) {
        if(loadBalancer == null) this.loadBalancer = new RandomLoadBalancer();
        else this.loadBalancer = loadBalancer;
    }



    @Override
    public InetSocketAddress lookupService(String serviceName, RpcRequest rpcRequest) {
        CuratorFramework zkClient = CuratorUtils.getZkClient();
        List<String> serviceUrlList = CuratorUtils.getChildrenNodes(zkClient, serviceName);
        if (serviceUrlList == null || serviceUrlList.size() == 0) {
            throw new RpcException(RpcError.SERVICE_NOT_FOUND,serviceName);
        }
        String targetServiceUrl = loadBalancer.selectServiceAddress(serviceUrlList,rpcRequest);
        log.info("Successfully found the service address:[{}]", targetServiceUrl);
        String[] socketAddressArray = targetServiceUrl.split(":");
        String host = socketAddressArray[0];
        int port = Integer.parseInt(socketAddressArray[1]);
        return new InetSocketAddress(host, port);
    }
}
